package com.cn.zengzeng.spbzengzeng.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;

/**
 * @Description: 所有的定时任务都放在一个线程池中，定时任务启动时使用不同都线程。
 * @Author: zhangzengzeng
 * @Date: 2021/6/30 18:04
 */
@Configuration
public class ScheduleConfig implements SchedulingConfigurer , AsyncConfigurer {
    /** 异步处理 */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
        TaskScheduler taskScheduler = taskScheduler();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

    /**
     * 定时任务多线程处理
     * @Auther zhangzengzeng
     * @Date 2021/7/7 14:29
     * @return org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
     **/
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskScheduler taskScheduler(){
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(20);
        scheduler.setThreadNamePrefix("task-");
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        return scheduler;
    }

    /**
     * @Auther zhangzengzeng
     * @Description  异步处理
     * @Date 2021/7/7 14:29
     * @return java.util.concurrent.Executor
     **/
    @Override
    public Executor getAsyncExecutor(){
        return taskScheduler();
    }

    /**
     * @Auther zhangzengzeng
     * @Description 异步处理 异常
     * @Date 2021/7/7 14:30
     * @return org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
     **/
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}